package com.dcy.system.filter.web.filter;

import com.dcy.system.filter.web.common.LogWebCommon;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 使用 Servlet Filter 生成请求的 trace 信息
 *
 * @author YuChangjiang
 */
public class LogServletFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean isFirstRequest = !isAsyncDispatch(request);
        if (isFirstRequest) {
            try {
                LogWebCommon.loadInstance().preHandle(request);

                // 把traceId放入response的header，为了方便有些人有这样的需求，从前端拿整条链路的traceId
                // response.addHeader(TLogConstants.TLOG_TRACE_KEY, TLogContext.getTraceId());

                filterChain.doFilter(request, response);
            } finally {
                if (!isAsyncStarted(request)) {
                    LogWebCommon.loadInstance().afterCompletion();
                }
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
